package filter;

import com.alibaba.fastjson.JSON;
import utils.JwtUtil;
import dto.ResultDto;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/api/*")
public class ZAuthFilter implements Filter {

    private static final String LOGIN = "login.do" ;
    private static final String OPTIONS = "options" ;
    private static final String TOKEN_HEADER = "Authorization" ;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1.向下转型

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 2.获取请求方式 -- 对预检请求进行放行
        String method = request.getMethod();
        if(OPTIONS.equalsIgnoreCase(method)) {
            filterChain.doFilter(request, response);
            return ;
        }

        // 3.获取客户端请求的URI地址，对于实现登录的Servlet 进行放行
        String requestURI = request.getRequestURI();
        if(requestURI.endsWith(LOGIN)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 4.获取客户端发送过来 JWT 令牌字符串
        String token = request.getHeader(TOKEN_HEADER);
        if(token==null || "".equals(token)) {
            responseView(response,"请先登录") ;
            return ;
        }

        // 5.验证token
        try {
            JwtUtil.verify(token);

            String username = JwtUtil.getPayload(token, "username", String.class);
            if(username==null || "".equals(username)) {
                responseView(response,"解析token失败") ;
                System.out.println("解析");
                return;
            }
            // 验证成功，放行
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            responseView(response,"会话已失效，请重新登入") ;
        }

    }

    private void responseView(HttpServletResponse response, String message) throws IOException {
        ResultDto vo = new ResultDto();
        vo.setCode(401);
        vo.setMsg(message);

        response.setContentType("application/json;charset=utf-8");
        String json = JSON.toJSONString(vo);

        PrintWriter out = response.getWriter();
        out.print(json) ;

        out.flush();
        out.close();
    }


    @Override
    public void destroy() {

    }
}
